package com.lz.clazz.runtime;


import net.openhft.compiler.CachedCompiler;
import net.openhft.compiler.CompilerUtils;

import java.io.File;

/**
 * OpenHFTDemo..
 *
 * https://github.com/OpenHFT/Java-Runtime-Compiler
 *
 * @author Lizhong
 * @date 2019/7/10
 */
public class OpenHFTDemo {
    public static void main(String[] args) {
        System.out.println("hello");
        method01();

    }

    public static void method01() {
        // dynamically you can call
        String className = "com.lz.clazz.runtime.MyClass";
        String javaCode = "package com.lz.clazz.runtime;\n" +
                "public class MyClass implements Runnable {\n" +
                "    public void run() {\n" +
                "        System.out.println(\"Hello World\");\n" +
                "    }\n" +
                "}\n";
        Class aClass = null;

        Runnable runner = null;
        // E:\gihubSource\TestDir\java-all-test\java-se\src\main\java

        // 得到项目路径，
        String udir = System.getProperty("user.dir");
        // 生成.java原文件
        CompilerUtils.writeBytes(new File(udir + "\\java-se\\src\\main\\java\\" +
                className.replace(".", File.separator) + ".java"), javaCode.getBytes());
        try {
            // 不生成任何文件
            // aClass = CompilerUtils.CACHED_COMPILER.loadFromJava(className, javaCode);
            String path = Thread.currentThread().getContextClassLoader().getResource(File.separator).getPath();
            path = path.substring(0, path.lastIndexOf("/"));
            String[] split = className.split("\\.");


            // bug，可以生成class
            CachedCompiler classpath = new CachedCompiler(null,
                    new File(path));
            aClass = classpath.loadFromJava(className, javaCode);
            runner = (Runnable) aClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        runner.run();
    }
}
